<template>
  <v-menu
    v-model="dateMenu"
    :close-on-content-click="false"
    transition="scale-transition"
    offset-y
    :max-width="width"
    :min-width="width"
    :readonly="readonly"
  >
    <template v-slot:activator="{ on, attrs }">
      <v-text-field
        v-model="localDate"
        outlined
        :label="label"
        v-bind="$attrs"
        v-on="on"
        @change="()=>onTextDateEdit(localDate)"
        :readonly="readonly"
      ></v-text-field>
    </template>
    <v-date-picker
      v-model="isoDate"
      no-title
      :show-current="true"
      @input="onFinishDatePicker"
      :readonly="readonly"
    ></v-date-picker>
  </v-menu>
</template>

<script>
  import { useDateTimeFormat } from "@/composable";
  // 日期选择控件
  export default {
    name: "DatePicker",
    model: {
      prop: "date",
      event: "change"
    },

    props: {
      date: {
        // iso格式的日期字符串
        type: String,
        default: ""
      },
      withTime: {
        // 取每天最开始时间，加上utf8,hardcode。。返回时间日期格式
        type: Boolean,
        default: false
      },

      width: {
        type: Number,
        required: false,
        default: 290
      },
      label: {
        type: String,
        required: false,
        default: "选择日期"
      },
      readonly: {
        type: Boolean,
        required: false,
        default: false
      }
    },
    setup(){
      const { simpleDateFormat, dateToISOString } = useDateTimeFormat()
      return { simpleDateFormat, dateToISOString }
    },
    data() {
      return {
        dateMenu: false,
        localDate: "",
        isoDate: new Date().toISOString()
      };
    },

    mounted() {
      this.localDate = this.simpleDateFormat(this.date, "YYYY-MM-DD");
      this.isoDate = this.dateToISOString(this.date);
    },

    watch: {
      date(val) {
        // if(this.withTime){
        //   this.localDate = this.simpleDateFormat(val, "YYYY-MM-DD HH:mm:ss");
        // }else{
        //   this.localDate = this.simpleDateFormat(val, "YYYY-MM-DD");
        // }
        this.localDate = this.simpleDateFormat(val, "YYYY-MM-DD");
        this.isoDate = this.dateToISOString(val);
      }
    },

    methods: {
      onTextDateEdit(localDate){
        console.log(localDate)
        let date = localDate
        // localDate一直是"YYYY-MM-DD"格式字符串，这样响应DatePicker时日期，但是isoDate和date可能希望带时分秒
        if(this.withTime){
          date += " 00:00:00+08:00"
        }
        this.isoDate = this.dateToISOString(date);
        this.dateMenu = false;
        this.$emit("change", date);
      },
      onFinishDatePicker() {
        let date = this.isoDate
        // 返回的时候加上时区
        if(this.withTime){
          date += "T00:00:00+08:00"
        }
        this.$emit("change", date);
        this.dateMenu = false;
      }
    }
  };
</script>